// 将token存储在vuex中 vuex刷新就没了 需要解决刷新就没了的问题
// import CookieJs from 'js-cookie'
import {
  getToken,
  setToken
} from '@/utils/auth.js'

import {
  sysLogin
} from '@/api/login.js'

import {
  sysProfile,
  sysUser
} from '@/api/user.js'

import {
  Message
} from 'element-ui'

const state = {
  token: getToken() || '',
  userInfo: ''
}

const mutations = {
  setToken(state, value) {
    state.token = value
    setToken(value)
  },
  setUserInfo(state, value) {
    state.userInfo = value
  },
  logout() {
    // mutations 调用mutations
    // this===this.$store
    // 加入token失效的vuex方法处理 清空token与用户信息
    this.commit('user/setToken', '')
    this.commit('user/setUserInfo', '')
  }
}

const actions = {
  // 登录
  async toLogin(store, from) {
    const res = await sysLogin(from)
    Message.success('登录成功')
    store.commit('setToken', res.data)
  },
  // 获取用户信息 调用接口获取用户信息并存储
  async getUserInfo({
    commit
  }) {
    const res = await sysProfile()
    const res2 = await sysUser(res.data.userId)
    commit('setUserInfo', Object.assign({}, res.data, res2.data))
  }
}

const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
